import json
import os

import pytest

from utils.logger_util import logger
from utils.request_util import Request, host

log=logger.getlog()

@pytest.fixture(scope='function')
def view_price_record_schema():
    yield {
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
        "code": {
            "type": "integer"
        },
        "data": {
            "type": ["object","null"],
            "properties": {
                "total": {
                    "type": "integer"
                },
                "records": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "prizeId": {
                                "type": "integer"
                            },
                            "prizeName": {
                                "type": "string"
                            },
                            "description": {
                                "type": "string"
                            },
                            "imageUrl": {
                                "type": "string"
                            },
                            "price": {
                                "type": "number"
                            }
                        },
                        "additionalProperties": False,
                        "required": [
                            "prizeId",
                            "prizeName",
                            "description",
                            "imageUrl",
                            "price"
                        ]
                    }
                }
            },
            "additionalProperties": False,
            "required": [
                "total",
                "records"
            ]
        },
        "msg": {
            "type": "string"
        }
    },
    "additionalProperties": False,
    "required": [
        "code",
        "data",
        "msg"
    ]
}

@pytest.fixture(scope="class")
def create_price_schema():
    yield  {
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
        "code": {
            "type": "integer"
        },
        "data": {
            "type": "integer"
        },
        "msg": {
            "type": "string"
        }
    },
    "additionalProperties": False,
    "required": [
        "code",
        "data",
        "msg"
    ]
}

@pytest.fixture(scope="function")
def verify_prize_creation(db_util):
    """
    验证奖品创建的夹具
    
    Args:
        db_util: 数据库工具实例
        
    Returns:
        function: 验证函数，接收prize_id和expected_data参数
    """
    def verify_function(prize_id, expected_data):
        """
        验证奖品是否成功创建并且数据正确
        
        Args:
            prize_id: 新创建的奖品ID
            expected_data: 期望的奖品数据字典
        """
        try:
            # 通过prize_id精确查询数据库记录
            sql = "SELECT id, name, description, price FROM prize WHERE id = :prize_id"
            result = db_util.execute_query(sql, {"prize_id": prize_id})

            # 验证记录存在
            assert result is not None and len(result) > 0, f"数据库中未找到ID为{prize_id}的奖品记录"

            record = result[0]
            log.info(f"查询到的奖品记录: {record}")

            # 验证ID匹配
            assert record['id'] == prize_id, f"数据库记录ID({record['id']})与期望ID({prize_id})不匹配"

            # 验证字段值
            if 'prizeName' in expected_data:
                assert record['name'] == expected_data['prizeName'], \
                    f"奖品名称不匹配: 数据库({record['name']}) vs 期望({expected_data['prizeName']})"

            if 'description' in expected_data:
                assert record['description'] == expected_data['description'], \
                    f"奖品描述不匹配: 数据库({record['description']}) vs 期望({expected_data['description']})"

            if 'price' in expected_data:
                assert record['price'] == expected_data['price'], \
                    f"奖品价格不匹配: 数据库({record['price']}) vs 期望({expected_data['price']})"

            log.info(f"奖品ID {prize_id} 的数据库验证通过")
            return True

        except Exception as e:
            log.error(f"验证奖品创建失败: {e}")
            raise

    yield verify_function



# ... existing code ...

@pytest.fixture(scope="function",autouse=False)
def purge_after_each_test(purge_all_tables):
    """
    本目录下每个测试用例执行完成后
    依赖全局的 purge_all_tables 夹具实现实际清库逻辑
    """
    yield


@pytest.fixture(scope='function')
def create_six_price(get_token):
    price_infos= [
        {
            'prizeName': 'iPhone 15 Pro',
            'description': '旧款',
            'price': 8000
        },
        {
            'prizeName': 'iPhone 16 Pro',
            'description': '较新',
            'price': 8011
        },
        {
            'prizeName': 'iPhone 17 Pro',
            'description': '新款',
            'price': 8999
        },
        {
            'prizeName': '小米 15 Pro',
            'description': '旧款',
            'price': 3999
        },
        {
            'prizeName': '小米 16 Pro',
            'description': '较新',
            'price': 4999
        },
        {
            'prizeName': '小米 17 Pro',
            'description': '新款',
            'price': 5999
        }
    ]

    for price_info in price_infos:
        """创建三个奖品，给查看奖品列表添加上下文"""
        picture_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'picture-file')
        picture_dir = os.path.abspath(picture_dir)

        image_files = []
        for file in os.listdir(picture_dir):
            file_path = os.path.join(picture_dir, file)
            if os.path.isfile(file_path) and file.lower().endswith(('.jpg', '.png', 'jpeg')):
                image_files.append(file_path)

        image_files.sort()
        first_file_path = image_files[0]
        log.info(f"准备创建奖品，使用图片: {first_file_path}")
        log.info(f"奖品信息: {price_info}")
        headers = {
            'user_token': get_token
        }
        param_json = json.dumps({
            'prizeName': price_info['prizeName'],
            'description': price_info['description'],
            'price': price_info['price']
        })

        with open(first_file_path, 'rb') as f:
            files = {
                'param': (None, param_json, 'application/json'),
                'prizePic': (first_file_path, f, 'image/png' if first_file_path.endswith('.png') else 'image/jpeg')
            }
            r = Request().post(url=host + 'prize/create', files=files, headers=headers)
            r.raise_for_status()
            assert r.json().get('code') == 200, f"创建奖品失败，业务码: {r.json().get('code')}, 消息: {r.json().get('msg')}"

    yield price_infos


